package com.lanou3g.code0523.dynamic;

import com.lanou3g.code0523.permission.BaseFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@WebFilter(filterName = "RandomFilter",servletNames = "RandomServlet")
public class RandomFilter extends BaseFilter {
    @Override
    public void doFilter(HttpServletRequest servletRequest,
                         HttpServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        //思路
        //当第一次访问 资源的时候,根据servlet输出的结果
        //生成一个html的文件
        //之后 只要这个html文件存在,那么就不去访问servlet了
        //而是直接把这个html返回
        //动态页面静态化,其实就是缓存
        //真正会用Redis

        ServletContext app=servletRequest.getServletContext();
        String filePath=app.getRealPath("")+File.separator+"random.html";
        File file = new File(filePath);
        if (!file.exists()){
            //生成html文件
            MyResponse Myresponse =new MyResponse(servletResponse,servletRequest.getServletContext());
            filterChain.doFilter(servletRequest,Myresponse);
            Myresponse.writeFile();
        }
        //请求转发
        servletRequest.getRequestDispatcher("/random.html").forward(servletRequest,servletResponse);


    }
}
